package com.wuhainan.beelzebub.service.system;

import com.wuhainan.beelzebub.common.BaseService;
import com.wuhainan.beelzebub.entity.system.Menu;
import com.wuhainan.beelzebub.repository.system.MenuRepository;
import com.wuhainan.beelzebub.utils.Constant;
import com.wuhainan.beelzebub.utils.PageInfo;
import com.wuhainan.beelzebub.utils.TableData;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <br>Created by 吴海南 on 2017-12-18.
 * <br>星期一 at 下午 3:05.
 */
@Service
public class MenuService extends BaseService<Menu> {
    @Resource
    private MenuRepository repository;

    public List<Menu> findAll() {
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        return repository.findAll(sort);
    }

    public TableData findMenuPage(PageInfo pageInfo, Menu menu) {
        Page<Menu> page = repository.findAll((root, cq, cb) -> {
            search(menu, cq, cb, root);//模糊查询
            return cq.getRestriction();
        }, pageable(pageInfo, sort(pageInfo, Sort.Direction.ASC, "id")));
        return tableData(page);
    }

    public Menu findMenuById(String id) {
        return repository.findOne(id);
    }

    /**
     * 保存菜单
     *
     * @param menu 菜单
     */
    public void saveMenu(Menu menu) {
        if (null == menu.getSort()) {
            Integer maxSort = 0;
            //如果父节点ID为空 设置查询条件 parentId为0
            if (null == menu.getParentId()) {
                Integer topId = maxSort(Constant.topId);
                if (null == topId) {
                    topId = 0;
                }
                menu.setSort(topId + 10);
                menu.setParentId(Constant.topId);
            } else {
                maxSort=maxSort(menu.getParentId());
                if (null == maxSort) {
                    menu.setSort(findMenuById(menu.getParentId()).getSort()*10+1);
                } else {
                    menu.setSort(maxSort + 1);
                }
            }

        }
        repository.save(menu);
    }

    private Integer maxSort(String parentId) {
        return repository.maxSort(parentId);
    }

    /**
     * 删除菜单 设置删除状态为true
     *
     * @param menu 菜单
     */
    public void deleteMenu(Menu menu) {
        menu.setStatuses(false);
//        menu.setModifyDate(new Date());
        repository.save(menu);
    }

    /**
     * 还原删除的菜单
     *
     * @param menu 菜单
     */
    public void restoreMenu(Menu menu) {
        menu.setStatuses(true);
//        menu.setModifyDate(new Date());
        repository.save(menu);
    }
}
